package com.fangs.kotlin_banner

import android.text.TextUtils
import com.fangs.kotlin_banner.utils.ProxyCacheUtils
import com.ivans.videocache.file.FileNameGenerator

class MyFileNameGenerator : FileNameGenerator {
    override fun generate(url: String): String {
        val extension = getExtension(url)
        val dotIndex = url.lastIndexOf('.')
        if (url.length > 18 && dotIndex > 18) {
            return url.substring(dotIndex - 18)
        }
        val name = ProxyCacheUtils.computeMD5(url)
        return if (TextUtils.isEmpty(extension)) name else "$name.$extension"
    }

    private fun getExtension(url: String): String {
        val dotIndex = url.lastIndexOf('.')
        val slashIndex = url.lastIndexOf('/')
        return if (dotIndex != -1 && dotIndex > slashIndex && dotIndex + 2 + MAX_EXTENSION_LENGTH > url.length) url.substring(
            dotIndex + 1
        ) else ""
    }

    companion object {
        private const val MAX_EXTENSION_LENGTH = 4
    }
}